package sshFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.commons.net.telnet.TelnetClient;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;

public class Shell {
	private static TelnetClient telnet = new TelnetClient();
	private PrintStream out;

	private static InputStream in;
	private char prompt = '$';
	private static SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMddHH");// 设置日期格式
	// 普通用户结束
	public Shell(String ip, int port, String user, String password, String fileName) {
		try {
			// System.out.println("准备执行：");
			telnet.connect(ip, port);
			in = telnet.getInputStream();
			out = new PrintStream(telnet.getOutputStream());
			write("SZHQ");
			write("Huqiao@123");
			System.out.println("登录成功.");
			// write("SET AMO:NAME=\"OMMB8\"");
			// write("FDD_QUERYCELLSTATUS:SUBNET=450304,NE=194871,EUTRANCELLID=1;");
			// System.out.println("执行成功.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** * 写操作 * * @param value */
	public void write(String value) {
		try {
			out.println(value);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** * 关闭连接 */
	public void disconnect() {
		try {
			telnet.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取分析结果
	 *
	 * @parampattern
	 * @return
	 */
	public static String readUntil(int count) {
		String flag = "";
		BufferedReader br = null;
		try {
//			 char lastChar = pattern.charAt(pattern.length() - 1);

			char ch = (char) in.read();
			// while (true) {
			// sb.append(ch);
			// if (ch == lastChar) {
			// if (sb.toString().endsWith(pattern)) {
			// return sb.toString();
			// }
			// }
//			in = telnet.getInputStream();
			br = new BufferedReader(new InputStreamReader(in, "gbk"));
			int b = 0;
//			int count =0;
//		      while((b=in.read())!=-1){
//		    	  System.out.println("count:"+count);
//		          count++;
//		        }
//			System.out.println(count);
			String line = null;
			int i = 0;
			boolean flag1 = false;
			while (br.ready()) {
//				System.out.println(br.ready());
				StringBuffer sb = new StringBuffer();
//			while ((line = br.readLine()) != null) {
//				if (pattern.startsWith("SET")) {
//					sb.append(line);
//					System.out.println(sb.toString());
//					FileUtils.writeStringToFile(new File("D://zhangbin//"+df1.format(new Date())+".txt"), sb.toString(), "gb2312", true);
//					return sb.toString();
//				}
				line = br.readLine();
//				if ("".equals(line)) {
//					continue;
//				}
				
				
				sb.append(line.replaceAll("\\[2K", "").replaceAll("\\[D", "").trim()).append("\n");
//				System.out.println(sb.toString());
				System.out.println(sb.toString());
				Pattern pattern1 = Pattern.compile("记录数");
				Pattern pattern2 = Pattern.compile("成功");
				Pattern pattern3 = Pattern.compile("SET");
//				Pattern pattern4 = Pattern.compile("结果");
				Matcher matcher = pattern1.matcher(sb.toString());
				Matcher matcher2 = pattern2.matcher(sb.toString());
				Matcher matcher3 = pattern3.matcher(line);
//				Matcher matcher4 = pattern4.matcher(line);
			
				
				String outStr = "";
				if (sb.toString().length()>= 100) {
					outStr = sb.toString().substring(0, 100);
				}else{
					outStr = sb.toString();
				}
				if (matcher3.find()) {
					i++;
//					sb.append("\n");
//					System.out.println(sb.toString());
//					FileUtils.writeStringToFile(new File("D://zhangbin//"+df1.format(new Date())+".txt"), sb.toString(), "gb2312", true);
//					FileUtils.writeStringToFile(new File("/root/file/shellResult/"+df1.format(new Date())+".txt"), sb.toString(), "gb2312", true);
				}
				
//				FileUtils.writeStringToFile(new File("D://zhangbin//"+df1.format(new Date())+".txt"), outStr, "gb2312", true);
				
//				if (!matcher.find() && !matcher2.find() && !matcher3.find()) {
//					sb.append("\n");
//					System.out.println(sb.toString());
//					FileUtils.writeStringToFile(new File("D://zhangbin//"+df1.format(new Date())+".txt"), sb.toString(), "gb2312", true);
					FileUtils.writeStringToFile(new File("/data/file/shellResult/zte/"+df1.format(new Date())+".txt"), outStr, "gb2312", true);
//					return sb.toString();
//				}
//				System.out.println(i);
				
				if (i== count) {
					System.out.println("i::"+i+"  count::"+count);
//					i++;
//					if (i == (count+6)) {
						return "";
//					}
					
				}
//				System.out.println("i::"+i+"  count::"+(count+4));
				
//				if (flag1) {
//					
//				}
//				
			
			}
			

			// ch = (char) in.read();
			// System.out.print(ch);
			// }
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
//		flag = sb.toString().substring(sb.toString().length() - 1, sb.toString().length());

//		System.out.println(sb.toString());
		return null;
	}

	/**
	 * 向目标发送命令字符串
	 *
	 * @paramcommand
	 * @return
	 */
	public void sendCommand(String command) {
		try {
			write(command);
//			return "";
//			return readUntil(command);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		return null;
	}

	public static void main(String[] args) {
		Properties properties = new Properties();
		InputStream inputStream = Shell.class.getClassLoader().getResourceAsStream("configzte.properties");
		try {
			properties.load(inputStream);
			Timer timer = new Timer();
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					// 检测文件夹并根据时间拆分为多个文件
					checkFileAndUpload checkFileClass = new checkFileAndUpload();
					
					//拆分多个可执行文件
					/*Object[] files = checkFileClass.getFiles(properties.getProperty("checkFilePath")).toArray();
					for (int i = 0; i < files.length; i++) {
						checkFileClass.analysisAndSplitFile(files[i].toString(),properties.getProperty("saveFilePath"));
						checkFileClass.DeleFile(files[i].toString());
					}*/

					// 上传文件
					SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// 设置日期格式
					Object[]  files = checkFileClass.getFiles(properties.getProperty("saveFilePath")).toArray();
					if (files.length > 0) {
						try {

							for (int i = 0; i < files.length; i++) {
								String fileName = new File(files[i].toString()).getName();
								fileName=fileName.substring(0, fileName.lastIndexOf("."));
								SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMddHH");// 设置日期格式
								String dateString = df1.format(new Date())+"00";
								
								System.out.println("dateString::"+dateString + " fileName::"+ fileName);
								if (dateString.equals(fileName)) {
									
									in = null;
									System.out.println("启动Telnet test4 ...");
									BufferedReader br1 = null;
									
//									String ip = "133.0.134.152";
//									int port = 21123;
//									String user = "wangyousjrh";
//									String password = "Zhongxing@123";
									String ip = properties.getProperty("IP");
									int port = 21123;
									String user = properties.getProperty("ftp_username");
									String password = properties.getProperty("ftp_password");
									Shell telnet1 = new Shell(ip, port, user, password, "");
						            BufferedReader br = new BufferedReader(new FileReader(files[i].toString()));
						            String s = null;
						            int count = 0;
						            while((s = br.readLine())!=null){
										Pattern pattern1 = Pattern.compile("SET");
										Matcher matcher = pattern1.matcher(s);
						            	if (matcher.find()) {
											count++;
										}
						            	System.out.println("count::"+count);
						                telnet1.sendCommand(s);
						                
						               
						            }
						            readUntil(count);
						            in.close();
						            br.close(); 
									
//									telnet1.sendCommand("SET AMO:NAME=\"OMMB8\";");
////									telnet1.sendCommand("FDD_STARTUPCELL:SUBNET=450304,NE=194611,EUTRANCELLID=1;");
////									telnet1.sendCommand("FDD_STARTUPCELL:SUBNET=450304,NE=194611,EUTRANCELLID=2;");
//									telnet1.sendCommand("FDD_SHUTDOWNCELL:SUBNET=450304,NE=194611,EUTRANCELLID=1;");
//									telnet1.sendCommand("FDD_SHUTDOWNCELL:SUBNET=450304,NE=194611,EUTRANCELLID=2;");
//									
////									telnet1.sendCommand("FDD_QUERYCELLSTATUS:SUBNET=450304,NE=194871,EUTRANCELLID=2;");
//						//
//									telnet1.sendCommand("SET AMO:NAME=\"OMMB7\";");
////									telnet1.sendCommand("FDD_SHUTDOWNCELL:SUBNET=450203,NE=702434,EUTRANCELLID=1;");
//									telnet1.sendCommand("FDD_STARTUPCELL:SUBNET=450203,NE=702434,EUTRANCELLID=1;");
////									telnet1.sendCommand("FDD_QUERYCELLSTATUS:SUBNET=450203,NE=700448,EUTRANCELLID=1;");
									telnet1.disconnect();
									File tempFile = new File(files[i].toString());
									tempFile.delete();
									System.out.println("删除已删除文件" +files[i].toString());
									System.out.println("end ...");
								}
								
							}

						} catch (Exception e) {
							
							System.out.println(e.getMessage()+ properties.getProperty("recordFilePath"));
							checkFileClass.writeRecord("运行错误：" + e.getMessage(),
									properties.getProperty("recordFilePath"));
						}
						
					} 
					
					
				}
			}, 5000, 10000);

		} catch (IOException e) {
			e.printStackTrace();
		}
			
//		try {
//			System.out.println("启动Telnet test4 ...");
//			String ip = "133.0.134.152";
//			int port = 21123;
//			String user = "wangyousjrh";
//			String password = "Zhongxing@123";
//			Shell telnet1 = new Shell(ip, port, user, password, "lst.txt");
//			telnet1.sendCommand("SET AMO:NAME=\"OMMB8\";");
////			telnet1.sendCommand("FDD_STARTUPCELL:SUBNET=450304,NE=194611,EUTRANCELLID=1;");
////			telnet1.sendCommand("FDD_STARTUPCELL:SUBNET=450304,NE=194611,EUTRANCELLID=2;");
//			telnet1.sendCommand("FDD_SHUTDOWNCELL:SUBNET=450304,NE=194611,EUTRANCELLID=1;");
//			telnet1.sendCommand("FDD_SHUTDOWNCELL:SUBNET=450304,NE=194611,EUTRANCELLID=2;");
//			
////			telnet1.sendCommand("FDD_QUERYCELLSTATUS:SUBNET=450304,NE=194871,EUTRANCELLID=2;");
////
//			telnet1.sendCommand("SET AMO:NAME=\"OMMB7\";");
////			telnet1.sendCommand("FDD_SHUTDOWNCELL:SUBNET=450203,NE=702434,EUTRANCELLID=1;");
//			telnet1.sendCommand("FDD_STARTUPCELL:SUBNET=450203,NE=702434,EUTRANCELLID=1;");
////			telnet1.sendCommand("FDD_QUERYCELLSTATUS:SUBNET=450203,NE=700448,EUTRANCELLID=1;");
//			telnet1.disconnect();
//			System.out.println("end ...");
//		} catch (Exception e) {
//			System.out.println("e:" + e.getMessage());
//			e.printStackTrace();
//		}
	}
}
